import Vue from "vue";
import {
    Message,
    MessageBox
} from "element-ui";
import axios from "axios";
import store from "../vuex/store";
import NProgress from "nprogress"; //进度条插件
import "nprogress/nprogress.css";
import qs from "qs";

//进度条配置
NProgress.configure({
    showSpinner: false
});
let instance = axios.create();
instance.interceptors.request.use(
    config => {
        NProgress.start();
        config.headers.tokenId =
            JSON.parse(window.sessionStorage.getItem("token")) || "";
        config.data = qs.stringify(config.data);
        return config;
    },
    error => {
        Promise.reject(error);
    }
);

// respone拦截器
instance.interceptors.response.use(
    response => {
        NProgress.done();
        const code = response.data.code;
        if (code === 0) {
            return response;
        } else if (code === 8888) {
            store.dispatch("loginOut");
        } else {
            MessageBox.alert(response.data.msg, "温馨提示", {});
        }
    },
    error => {
        // Message({
        //     message: error.message,
        //     type: 'error',
        //     duration: 3 * 1000 //3s后消失
        // });
        // return Promise.reject(error);
    }
);

export const fatch = function ({
    method = "get",
    url,
    params,
    customErr = false
}) {
    return new Promise((resolve, reject) => {
        instance({
                method: method,
                url: url,
                [method === "post" ? "data" : "params"]: params
            })
            .then(
                response => {
                    if (customErr) {
                        resolve(response.data);
                    } else {
                        if (response.data.code === 0) {
                            resolve(response.data.data);
                        } else {
                            // 错误提示
                            this.$message({
                                showClose: true,
                                message: response.data.msg,
                                type: "warning"
                            });
                        }
                    }
                },
                error => {
                    reject(error);
                }
            )
            .catch(error => {
                reject(error);
            });
    });
};
